import java.util.*;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28318
 * Date: 2025-11-15
 * Time: 16:58
 */
public class BinaryTree {

    static class TreeNodeCharacter {
        public char val;
        public TreeNodeCharacter left;//左孩子的引用
        public TreeNodeCharacter right;//右孩子的引用

        public TreeNodeCharacter() {
        }

        public TreeNodeCharacter(char val) {
            this.val = val;
        }
    }

    static class TreeNodeInteger {
        public int val;
        public TreeNodeInteger left;//左孩子的引用
        public TreeNodeInteger right;//右孩子的引用

        public TreeNodeInteger() {
        }

        public TreeNodeInteger(int val) {
            this.val = val;
        }
    }

    /**
     * 创建一棵二叉树 返回这棵树的根节点
     *
     * @return
     */
    public TreeNodeCharacter createTree() {
        TreeNodeCharacter A = new TreeNodeCharacter('A');
        TreeNodeCharacter B = new TreeNodeCharacter('B');
        TreeNodeCharacter C = new TreeNodeCharacter('C');
        TreeNodeCharacter D = new TreeNodeCharacter('D');
        TreeNodeCharacter E = new TreeNodeCharacter('E');
        TreeNodeCharacter F = new TreeNodeCharacter('F');
        TreeNodeCharacter G = new TreeNodeCharacter('G');
        TreeNodeCharacter H = new TreeNodeCharacter('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.right = F;
        D.left = G;
        E.right = H;
        return A;
    }

    public TreeNodeInteger createTree1() {
        TreeNodeInteger A = new TreeNodeInteger(1);
        TreeNodeInteger B = new TreeNodeInteger(2);
        TreeNodeInteger C = new TreeNodeInteger(3);
        TreeNodeInteger D = new TreeNodeInteger(4);
        TreeNodeInteger E = new TreeNodeInteger(5);
        TreeNodeInteger F = new TreeNodeInteger(6);
        TreeNodeInteger G = new TreeNodeInteger(7);
        TreeNodeInteger H = new TreeNodeInteger(8);
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.right = F;
        D.left = G;
        E.right = H;
        return A;
    }

    // 前序遍历
    public void preOrder(TreeNodeCharacter root) {
        if (root == null){
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }

    // 中序遍历
    public void inOrder(TreeNodeCharacter root) {
        if (root == null){
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }

    // 后序遍历
    public void postOrder(TreeNodeCharacter root) {
        if (root == null){
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }

    // 树的节点数
    public int nodeSize;

    /**
     * 获取树中节点的个数：遍历思路
     */
    public void size(TreeNodeCharacter root) {
        if (root == null){
            return;
        }
        this.nodeSize++;
        size(root.left);
        size(root.right);
    }

    /**
     * 获取节点的个数：子问题的思路
     *
     * @param root
     * @return
     */
    public int size2(TreeNodeCharacter root) {
        if (root == null){
            return 0;
        }
        return 1 + size2(root.left) + size2(root.right);
    }


    /*
     获取叶子节点的个数：遍历思路
     */
    public int leafSize = 0;

    public void getLeafNodeCount1(TreeNodeCharacter root) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            this.leafSize++;
        }
        getLeafNodeCount1(root.left);
        getLeafNodeCount1(root.right);
    }

    /*
     获取叶子节点的个数：子问题
     */
    public int getLeafNodeCount2(TreeNodeCharacter root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left) + getLeafNodeCount2(root.right);
    }

    /*
    获取第K层节点的个数
     */
    public int getKLevelNodeCount(TreeNodeCharacter root, int k) {
        if (root == null) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left, k - 1) + getKLevelNodeCount(root.right, k - 1);
    }

    /*
     获取二叉树的高度
     时间复杂度：O(N)
     */
    public int getHeight(TreeNodeCharacter root) {
        if (root == null) {
            return 0;
        }
        int left = getHeight(root.left);
        int right = getHeight(root.right);
        return left > right ? left + 1 : right + 1;
    }

    // 检测值为value的元素是否存在
    public TreeNodeCharacter find(TreeNodeCharacter root, char val) {
        if (root == null) {
            return null;
        }
        if (root.val == val) {
            return root;
        }
        TreeNodeCharacter left = find(root.left, val);
        TreeNodeCharacter right = find(root.right, val);
        if (left != null) {
            return left;
        }
        if (right != null) {
            return right;
        }
        return null;
    }

    //层序遍历
    public void levelOrder(TreeNodeCharacter root) {
        Queue<TreeNodeCharacter> stack = new ArrayDeque<>();
        stack.offer(root);
        while (!stack.isEmpty()) {
            int size = stack.size();
            for (int i = 0; i < size; i++) {
                root = stack.poll();
                System.out.print(root.val + " ");
                if (root.left != null) {
                    stack.offer(root.left);
                }
                if (root.right != null) {
                    stack.offer(root.right);
                }
            }
        }
        System.out.println();
    }

    // 判断一棵树是不是完全二叉树
    public boolean isCompleteTree(TreeNodeCharacter root) {
        Queue<TreeNodeCharacter> stack = new LinkedList<>();
        while (root != null) {
            stack.offer(root);
            stack.offer(root.left);
            stack.offer(root.right);
            root = stack.poll();
        }
        for (int i = 0; i < stack.size(); i++) {
            root = stack.poll();
            if (root != null) {
                return false;
            }
        }
        return true;
    }

//    翻转二叉树
    public TreeNodeCharacter invertTree(TreeNodeCharacter root) {
        if (root == null) {
            return null;
        }
        TreeNodeCharacter ret = new TreeNodeCharacter(root.val);
        ret.left = invertTree(root.right);
        ret.right = invertTree(root.left);
        return ret;
    }

//    检查两颗二叉树是否相同
    public boolean isSameTree(TreeNodeCharacter p, TreeNodeCharacter q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        if (p.val != q.val) {
            return false;
        }
        if (isSameTree(p.left, q.left) && isSameTree(p.right, q.right)) {
            return true;
        }
        return false;
    }

//    判断二叉树树是否对称
    public boolean isSymmetric(TreeNodeCharacter root) {
        if (root == null) {
            return true;
        }
        return isSymmetric(root.left, root.right);
    }

    private boolean isSymmetric(TreeNodeCharacter p, TreeNodeCharacter q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        if (p.val != q.val) {
            return false;
        }
        if (isSymmetric(p.left, q.right) && isSymmetric(p.right, q.left)) {
            return true;
        }
        return false;
    }

//    判断root树中是否含有与subRoot树结构与数值一致的子树
    public boolean isSubtree(TreeNodeCharacter root, TreeNodeCharacter subRoot) {
        if (root == null && subRoot == null) {
            return true;
        }
        if (root == null || subRoot == null) {
            return false;
        }
        boolean ret = false;
        if (root.val == subRoot.val) {
            ret = isSameTree(root, subRoot);
        }
        return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot) || ret;
    }

//    判断二叉树是否是平衡二叉树
    public boolean isBalanced(TreeNodeCharacter root) {
        if (root == null) {
            return true;
        }
        int left = getHeight(root.left);
        int right = getHeight(root.right);
        int intAbs = Math.abs(left - right);
        if (intAbs > 1) {
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }

//    依据完整的前序遍历创建二叉树
    public int i = 0;
    public TreeNodeCharacter createTreePre(String str) {
        TreeNodeCharacter ret = null;
        if (str.charAt(i) == '#') {
            i++;
        }else {
            ret = new TreeNodeCharacter(str.charAt(i));
            i++;
            ret.left = createTreePre(str);
            ret.right = createTreePre(str);
        }
        return ret;
    }

//    依据中序和后序遍历序列构造二叉树
    public int ip = 0;
    public TreeNodeInteger buildTreePost(int[] inorder, int[] postorder) {
        ip = postorder.length - 1;
        TreeNodeInteger root = buildTreePost(inorder, postorder, 0, inorder.length - 1);
        return root;
    }

    public TreeNodeInteger buildTreePost(int[] inorder, int[] postorder, int isStart, int isEnd) {
        if (isStart > isEnd) {
            return null;
        }
        TreeNodeInteger root = new TreeNodeInteger(postorder[ip]);
        int isIndex = findVal(inorder, isStart, isEnd, postorder[ip]);
        ip++;
        root.right = buildTreePost(inorder, postorder, isIndex + 1, isEnd);
        root.left = buildTreePost(inorder, postorder, isStart, isIndex - 1);
        return root;
    }

//    依据前序和中序遍历构造二叉树
//    public int ip = 0;
    public TreeNodeInteger buildTreePre(int[] preorder, int[] inorder) {
        ip = 0;
        TreeNodeInteger root = new TreeNodeInteger();
        root = buildTreePre(preorder, inorder, 0, inorder.length - 1);
        return root;
    }

    private TreeNodeInteger buildTreePre(int[] preorder, int[] inorder, int isStart, int isEnd) {
        if (isStart > isEnd) {
            return null;
        }
        TreeNodeInteger root = new TreeNodeInteger(preorder[ip]);
        int isIndex = findVal(inorder, isStart, isEnd, preorder[ip]);
        ip--;
        root.left = buildTreePre(preorder, inorder, isStart, isIndex - 1);
        root.right = buildTreePre(preorder, inorder, isIndex + 1, isEnd);
        return root;
    }

    private int findVal(int[] nums, int start, int end, int val) {
        for (int i = start; i <= end; i++) {
            if (nums[i] == val) {
                return i;
            }
        }
        return -1;
    }

//    非递归前序遍历
    public List<Integer> preorderTraversal(TreeNodeInteger root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNodeInteger> stack = new Stack<>();
        TreeNodeInteger cur = root;
        while (!stack.isEmpty() || cur != null) {
            if (cur == null) {
                cur = stack.pop().right;
            }else {
                list.add(cur.val);
                stack.push(cur);
                cur = cur.left;
            }

        }
        return list;
    }

//    非递归中序遍历
    public List<Integer> inorderTraversal(TreeNodeInteger root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNodeInteger> stack = new Stack<>();
        TreeNodeInteger cur = root;
        while (!stack.isEmpty() || cur != null) {
            if (cur == null) {
                cur = stack.pop();
                list.add(cur.val);
                cur = cur.right;
            }else {
                stack.push(cur);
                cur = cur.left;
            }
        }
        return list;
    }

//    非递归后序遍历
    public List<Integer> postorderTraversal(TreeNodeInteger root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        TreeNodeInteger cur = root;
        TreeNodeInteger prev = new TreeNodeInteger();
        Stack<TreeNodeInteger> stack = new Stack<>();
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNodeInteger top = stack.peek();
            if (top.right == null || top.right == prev) {
                list.add(top.val);
                stack.pop();
                prev = top;
            } else {
                cur = top.right;
            }
        }
        return list;
    }

//    求二叉树中某两个节点的最近公共祖先
    public TreeNodeInteger lowestCommonAncestor(TreeNodeInteger root, TreeNodeInteger p, TreeNodeInteger q) {
        if (root == null) {
            return null;
        }
        if (root == p || root == q) {
            return root;
        }
        TreeNodeInteger left = lowestCommonAncestor(root.left, p, q);
        TreeNodeInteger right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) {
            return root;
        } else if (left != null) {
            return left;
        } else {
            return right;
        }
    }

    public TreeNodeInteger lowestCommonAncestor1(TreeNodeInteger root, TreeNodeInteger p, TreeNodeInteger q) {

        return null;
    }

//    获取树上从root节点到index节点的路径栈
    public Stack<TreeNodeInteger> getIntegerPath(TreeNodeInteger root, TreeNodeInteger index) {
        Stack<TreeNodeInteger> stack = new Stack<>();

        return stack;
    }

//    自底向上，自左向右的层序遍历
    public List<List<Integer>> levelOrderBottom(TreeNodeInteger root) {
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNodeInteger> stack = new ArrayDeque<>();
        stack.offer(root);
        while (!stack.isEmpty()) {
            int size = stack.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                root = stack.poll();
                list.add(root.val);
                if (root.left != null) {
                    stack.offer(root.left);
                }
                if (root.right != null) {
                    stack.offer(root.right);
                }
            }
            ret.add(0, list);
        }
        System.out.println();
        return ret;
    }

//    返回一个二维数组的层序遍历
    public List<List<Integer>> levelOrderList(TreeNodeInteger root) {
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNodeInteger> stack = new ArrayDeque<>();
        stack.offer(root);
        while (!stack.isEmpty()) {
            int size = stack.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                root = stack.poll();
                list.add(root.val);
                if (root.left != null) {
                    stack.offer(root.left);
                }
                if (root.right != null) {
                    stack.offer(root.right);
                }
            }
            ret.add(list);
        }
        System.out.println();
        return ret;
    }

//    根据二叉树创建字符串
    public String tree2str(TreeNodeInteger root) {
        if (root == null) {
            return null;
        }
        StringBuffer str = new StringBuffer();
        str.append(root.val);
        if (root.left != null) {
            str.append("(" + tree2str(root.left) + ")");
            if (root.right != null) {
                str.append("(" + tree2str(root.right) + ")");
            }
        } else {
            if (root.right != null) {
                str.append("()(" + tree2str(root.right) + ")");
            }
        }
        return str.toString();
    }
}

